package org.dk.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.dk.domain.DataResult;
import org.dk.em.DataResultEnum;
import org.dk.pageInfo.PageInfo2;
import org.dk.pojo.TbGoods;
import org.dk.pojo.TbItemCat;
import org.dk.service.GoodsService;
import org.dk.service.TbItemCatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Controller
@RequestMapping("goodsController")
public class GoodsController {

    @Reference
    private GoodsService goodsService;

     @Reference
     private TbItemCatService catService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @RequestMapping("toGoods")
    public String toGoods(){
            return "admin/goods";
        }

    @RequestMapping("selectAll")
    @ResponseBody
    public DataResult selectAll(String goodsName,@RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                @RequestParam(required = false, defaultValue = "5") Integer pageSize){
        PageInfo2<TbGoods> selevt = goodsService.selectBrand(goodsName,pageNum, pageSize);
        List<TbItemCat> list =catService.selectAll();
        Map<String,Object> map = new HashMap<>();
        map.put("page",selevt);
        map.put("list",list);
        return DataResult.buildDataResult(DataResultEnum.SUCCESS).setData(map);
    }

    @RequestMapping("deleteGoods")
    @ResponseBody
    public DataResult deleteGoods(@RequestParam("ids[]") Long[] ids){
        try {
            goodsService.deleteGoods(ids);
            return DataResult.buildDataResult(DataResultEnum.SUCCESS);
        }catch (Exception e){
            return DataResult.buildDataResult(DataResultEnum.ERROR);
        }
    }

    @RequestMapping("updateGoods")
    @ResponseBody
    public DataResult updateGoods(@RequestParam("ids[]") Long[] ids,String auditStatus){
        try {
            goodsService.updateGoods(ids,auditStatus);
            if(Objects.equals(auditStatus,"1")){
                String str = new Gson().toJson(ids);
                rocketMQTemplate.convertAndSend("item-goods",str);
            }
            return DataResult.buildDataResult(DataResultEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return DataResult.buildDataResult(DataResultEnum.ERROR);
        }
    }
}
